//--helper--
#include "program_mode.h"

void program_mode(  std::ostringstream & osstream
                  , quex::depythonize_c_lex & qlex
                  , quex::Token & token
                  , quex::Token & tokenNext
                  , std::vector<quex::Token> & tokens_before_token
                  , std::vector<quex::Token> & tokens_before_tokenNext
                  ){
  bool not_in_parentheses_block = true;
  while(
        token.type_id() != QUEX_TKN_TERMINATION &&
        token.type_id() != QUEX_TKN_PREPROCESSOR_MULTILINE_START ){
    //Write the non compilable tokens
    write_out(osstream, tokens_before_token);
    
    // Write the code
    if(token.type_id() != QUEX_TKN_BLOCK_OPEN
    && token.type_id() != QUEX_TKN_BLOCK_CLOSE
    && token.type_id() != QUEX_TKN_PREPROCESSOR_MULTILINE_END){
      osstream << token.get_text().c_str();}
    
    //Set the not_in_parentheses_block flag
    if(token.type_id() == QUEX_TKN_START_PARENTHESIS_BLOCK){
      not_in_parentheses_block = false;}
    else if(token.type_id() == QUEX_TKN_END_PARENTHESIS_BLOCK){
      not_in_parentheses_block = true;}
    
    //Check if it needs a semicolon
    if(
      tokenNext.type_id() != QUEX_TKN_BLOCK_OPEN &&  // avoid if();{
      token.type_id() != QUEX_TKN_BLOCK_OPEN &&  // avoid  if(){;
      token.type_id() != QUEX_TKN_BLOCK_CLOSE &&  // avoid if(){};
      token.type_id() != QUEX_TKN_SEMICOLON &&  // avoid printf();;
      token.type_id() != QUEX_TKN_PREPROCESSOR_MULTILINE_END && //
       is_in_buffer(tokens_before_tokenNext,QUEX_TKN_NEWLINE) &&  // Need a new line to add a semicolon
      !is_in_buffer(tokens_before_tokenNext,QUEX_TKN_BACKSLASH) && // We can escape a semicolon
      not_in_parentheses_block //avoid (;)
    ){
      osstream << ";";}
  
    //Check if we need to open or close a block
    if( tokenNext.type_id() == QUEX_TKN_BLOCK_OPEN && not_in_parentheses_block ){
      osstream << "{";}

    //Need to print newlines and spaces before the block closing
    if(tokenNext.type_id() == QUEX_TKN_BLOCK_CLOSE){
      print_many_block_close(osstream,qlex,token,tokenNext, tokens_before_token, tokens_before_tokenNext);}
    else{
      //Step forward one token
      token = tokenNext;
      tokens_before_token.swap(tokens_before_tokenNext);
      get_token(tokenNext,qlex,tokens_before_tokenNext);}}

  return;}


